package logic

import (
	"context"
	"encoding/json"
	"shopconnect/model/mysql"
	"shopconnect/model/redis"
	"strconv"
	"time"

	"shopconnect/shoprpc/internal/svc"
	"shopconnect/shoprpc/shoprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShopListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShopListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShopListLogic {
	return &ShopListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ShopListLogic) ShopList(in *shoprpc.ShopListRequest) (*shoprpc.ShopListResponse, error) {
	// todo: add your logic here and delete this line
	var shops []mysql.Products
	var lists []*shoprpc.ShopList
	key := "list" + strconv.Itoa(int(in.Page)) + strconv.Itoa(int(in.Size)) + in.Name
	result, err := redis.Rdb.Get(key).Result()
	if err != nil {
		query := mysql.DB.Debug()
		if in.Name != "" {
			query = query.Where("name like ?", "%"+in.Name+"%")
		}
		if in.Size != 0 && in.Page != 0 {
			query = query.Order("price desc").Offset(int((in.Page - 1) * in.Size)).Limit(int(in.Size)).Find(&shops)
		}
		marshal, _ := json.Marshal(&shops)
		redis.Rdb.Set(key, string(marshal), time.Hour*24)
	} else {
		json.Unmarshal([]byte(result), &shops)
	}

	for _, list := range shops {
		list1 := shoprpc.ShopList{
			Img:   list.Img,
			Video: list.Video,
			Name:  list.Name,
			Nums:  list.Nums,
			Intro: list.Intro,
			Price: float32(list.Price),
		}
		lists = append(lists, &list1)
	}
	return &shoprpc.ShopListResponse{List: lists}, nil
}
